<script setup>
import { useRouter } from 'vue-router';
import {deleteHandler,restartHandler,updateHandler} from '../../api/generic'
import { getReplicaSetListHandler } from '../../api/deployment';
import { ElMessage,ElMessageBox  } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import MatchPod from '../components/scheduling/MatchPod.vue';
import { onBeforeMount, ref } from 'vue';
import { d } from '@codemirror/legacy-modes/mode/d';
import { object2String ,obj2Yaml} from '../../utils/utils';
import CodeMirror from './CodeMirror.vue';
const router = useRouter()
const props = defineProps({
  resourceType: {
    type: String,
    default: 'Deployment'
  },
  clusterId:{
    type: String,
    required: true,
  },
  namespace:{
    type: String,
    default:'',
  },
  name:{
    type: String,
    required: true,
  },
  disabled:{
    type: Boolean,
    default: false
  },
  showScheduleOptions: {
    type: Boolean,
    default: false
  },
  item: {
    type: Object,
    default :{}
  }
})
const emits = defineEmits(['deleteRollback'])

// 删除的方法
const deleteItem = () => {
  let message = ''
  if (props.namespace == ''){
    message = `你确定要删除: ${props.resourceType}: ${props.name}吗？`
  }else {
    message = `你确定要删除命名空间: ${props.namespace} ${props.resourceType}: ${props.name}吗？`
  }
  ElMessageBox.confirm(
    message,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteHandler(props.clusterId, props.namespace, props.name,props.resourceType).then(
        (res) => {
          ElMessage({
              message: res.data.message,
              type: 'warning',
          })
        //   getList()
        //做回调函数
        emits('deleteRollback')
        }
      )
    })
    .catch(() => {
      return
    })

  
}
// 编辑的的方法
const editItem = (arg) => {
  console.log("编辑或复制资源:", props.clusterId,props.namespace,props.name)
  const resourceType = props.resourceType.toLowerCase()
  router.push({
    path: `/${resourceType}/edit`,
    query: {
      clusterId: props.clusterId,
      namespace: props.namespace,
      name: props.name,
      method: arg
    }
  })
}

// 重启的的方法
const restart = () => {
  console.log("重启的资源:", props.clusterId,props.namespace,props.resourceType,props.name)
  ElMessageBox.confirm(
    `你确定要重启集群:${props.clusterId}命名空间: ${props.namespace} ${props.resourceType} : ${props.name}吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      restartHandler(props.clusterId, props.namespace, props.resourceType,props.name).then(
        (res) => {
          ElMessage({
              message: res.data.message,
              type: 'success',
          })
        }
      )
    })
    .catch(() => {
      return
    })
}
let disableUpdateImageButton = ref(true)
const updateImages = ref(false)
const rollback = ref(false)
const rollbackSelected = ref()
const updateImagesFormRef = ref(false)
const activeName = ref(0)
const handleCommand = (command) => {
  console.log("你点击了",command)
  switch (command){
    case "updateImages":
      updateImages.value = true
      break;
    case "rollback":  
      rollback.value = true
      break;  
    default:
      break;
  }
}
const rollbackDeploymentHandler = (item,rsTemplate)=>{
      ElMessageBox.confirm(
    `你确定要回滚集群:${props.clusterId}命名空间: ${props.namespace} ${props.resourceType} : ${props.name}吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      item.spec.template = rsTemplate
      delete item.spec.template.metadata.labels["pod-template-hash"]
      updateHandler(props.clusterId, 
      props.namespace, 
      props.name,
      props.resourceType,
      item
    ).then(
        (res) => {
          rollback.value=false
          ElMessage({
              message: res.data.message,
              type: 'success',
          })
          //重新获取列表
          emits('deleteRollback')
        }
      )
    })
    .catch(() => {
      return
    })
}
const updateContainerImage = ()=>{
  updateImagesFormRef.value.validate((valid)=>{ 
    if(valid){
      //更新镜像
      console.log("修改后的值:",props.item)
      ElMessageBox.confirm(
    `你确定要更新集群:${props.clusterId}命名空间: ${props.namespace} ${props.resourceType} : ${props.name}的镜像吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      updateHandler(props.clusterId, 
      props.namespace, 
      props.name,
      props.resourceType,
      props.item
    ).then(
        (res) => {
          updateImages.value=false
          ElMessage({
              message: res.data.message,
              type: 'success',
          })
          //重新获取列表
          emits('deleteRollback')
        }
      )
    })
    .catch(() => {
      return
    })
    }else {
      ElMessage.warning("请输入镜像地址")
      disableUpdateImageButton.value = true
    }
  })
}
let rsList = ref([])
// 选择框展开调用接口查询数据
const visibleChanged = (visible)=>{
  console.log("visible:",visible)
  // 展开的时候去查询items
  if (visible) {
    // 调用查询列表的函数
    const labelSelector = object2String(props.item.spec.selector.matchLabels,",")
    const getData = {
      clusterId: props.clusterId,
      namespace: props.namespace,
      fieldSelector: '',
      labelSelector: labelSelector
    }
    getReplicaSetListHandler(getData).then(
      (res) => {
      let items = res.data.data.items
      //对items进行排序
      //[d,d,a,2,g,4] => items.sort()
      //负数 a在前面 a<b
      //正数 a在后面 a>b
      // 0 ab顺序不影响
      items.sort((a,b)=>
        a.metadata.annotations['deployment.kubernetes.io/revision']-
        b.metadata.annotations['deployment.kubernetes.io/revision']
      )
        rsList.value = res.data.data.items
        console.log(rsList.value)
      }
    )
  }
}
let containers = ref([]);
let yamlData = ref('');
const rollbackChanged = ()=>{
  console.log("选择回滚的版本是:",rollbackSelected.value)
  const item = JSON.parse(JSON.stringify(rollbackSelected.value))
  // 删除managedFields
  delete item.metadata.managedFields
  // 把apiVersion kind补上去
  const itemtemp = {
    "apiVersion": "apps/v1",
    "kind": "ReplicaSet",
    "metadata": item.metadata,
    "spec": item.spec
  }
  yamlData.value = obj2Yaml(itemtemp)
}
const rollbackDeployment =()=>{ 
  console.log("回滚的RS:",rollbackSelected.value.spec.template)
  console.log("当前的deploy配置:",props.item)
  rollbackDeploymentHandler(JSON.parse(JSON.stringify(props.item)),rollbackSelected.value.spec.template)
}

onBeforeMount(() => {
  if (props.item != null){
    if(['Deployment','StatefulSet','Daemonset'].includes(props.resourceType)){
    containers.value = props.item.spec.template.spec.containers
    }else if (props.resourceType == 'CronJob'){
      containers.value = props.item.spec.jobTemplate.spec.template.spec.containers
    }
  }
})

</script>

<template>
    <el-button :disabled="props.disabled" link type="warning" @click="deleteItem()">删除</el-button>
    <el-button :disabled="props.disabled" link type="warning" @click="restart()" v-if="['Deployment','StatefulSet','DaemonSet'].includes(props.resourceType)">重启</el-button>
    <el-button :disabled="props.disabled" link type="primary" @click="editItem('Update')">编辑</el-button>
    <el-button :disabled="props.disabled" link type="primary" @click="editItem('Copy')">复制</el-button>
    <div v-if="props.showScheduleOptions" style="display: inline;">
      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link">
          <el-button link type="primary" style="height: 26px; margin-left: 10px;" >更多
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
        </el-button>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="rollback" v-if="props.resourceType == 'Deployment'">回滚</el-dropdown-item>
            <el-dropdown-item command="updateImages">更新镜像</el-dropdown-item>
            <el-dropdown-item  v-if="props.resourceType != 'CronJob'">
              <MatchPod
              button-title="获取资源管理的Pod"
              button-name="关联Pod"
              :cluster-id="props.clusterId"
              :namespace="props.namespace"
              :resource-type="props.resourceType"
              :resource-name="props.name"
              field-selector=""
              :label-selector-obj="props.item.spec.selector.matchLabels"
              button-type=""
              ></MatchPod>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
    </el-dropdown>
    </div>
   <!-- 更新镜像 -->
   <el-dialog append-to-body width="70%" center draggable v-model="updateImages">
        <template #header="{ titleId, titleClass }">
            <div class="my-header">
                <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
                  <el-tag  class="el-tag" size="large" title="集群">
                    {{ props.clusterId }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="类型">
                    {{ props.resourceType }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="命名空间">
                    {{ props.namespace }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="资源名称">
                    {{ props.name }}
                  </el-tag>
                </div>
            </div>
        </template>
        <el-form 
        :model="containers"
        ref="updateImagesFormRef"
        >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane v-for="(c,index) in containers" 
          :label="c.name" 
          :name="index" 
          :key="c.name">
            <el-form-item label="镜像地址"
            :rules="[{required: true, message: '请输入镜像地址', trigger: 'blur'}]"
            :prop="index+'.image'"
            >
              <el-input v-model.trim="c.image" @change="()=>{disableUpdateImageButton=false}" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        </el-form>
        <template #footer>
          <div>
            <el-button @click="updateImages=false">取消</el-button>
            <el-button :disabled="disableUpdateImageButton" type="primary" @click="updateContainerImage()">确认</el-button>
        </div>
        </template>
    </el-dialog>
    <!-- 回滚 -->
   <el-dialog append-to-body width="70%" center draggable v-model="rollback">
        <template #header="{ titleId, titleClass }">
            <div class="my-header">
                <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
                  <el-tag  class="el-tag" size="large" title="集群">
                    {{ props.clusterId }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="类型">
                    {{ props.resourceType }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="命名空间">
                    {{ props.namespace }}
                  </el-tag>
                  >
                  <el-tag class="el-tag"  size="large" title="资源名称">
                    {{ props.name }}
                  </el-tag>
                </div>
            </div>
        </template>
        <div>
          <!-- 当前版本和回滚版本 -->
          <el-form-item label="当前版本:"
          >
            <span>{{ props.item.metadata.annotations["deployment.kubernetes.io/revision"] }}</span>
            </el-form-item>
          <el-form-item label="选择回滚版本:"
        >
            <el-select 
            value-key="metadata.name" 
            v-model="rollbackSelected" 
            placeholder="请选择回滚的版本" 
            @visible-change="visibleChanged"
            @change="rollbackChanged"
            >
              <el-option
                v-for="item in rsList"
                :key="item.metadata.name"
                :label="'版本:' + item.metadata.annotations['deployment.kubernetes.io/revision'] +' '+  item.metadata.annotations['kubernetes.io/change-cause']"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <!-- 展示yaml -->
           <CodeMirror v-model="yamlData" height="400px"></CodeMirror>
        </div>
        <template #footer>
          <div>
            <el-button @click="rollback=false">取消</el-button>
            <el-button  type="primary" @click="rollbackDeployment()">确认</el-button>
        </div>
        </template>
    </el-dialog>
</template>

<style scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
}
.el-tag {
  margin-left: 20px;
  margin-right: 20px;
  font-size: 20px;
}
</style>
